<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="样品检验/留样管理">
        <template slot="btn">

        </template>
      </modules-title>
    </div>
    <div style="padding:20px">
      <el-tabs type="border-card" v-model="activeIndex" @tab-click="tabClick">
        <el-tab-pane label="留样记录" name="1"></el-tab-pane>
        <el-tab-pane label="销毁记录" name="2"></el-tab-pane>
        <!--搜索-->
        <el-form :inline="true">
          <el-form-item label="状态" v-if="activeIndex === '1'" style="margin-right:40px">
            <el-select v-model="queryParams.search_type" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="样品关键字" style="margin-right:40px">
            <el-input v-model="queryParams.sample_name" placeholder="请输入样品关键字" />
          </el-form-item>
          <el-form-item>
            <el-button class="filter-item" type="primary" icon="el-icon-search" size="small"
              @click="handleQuery">查询
            </el-button>
            <el-button plain icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button class="filter-item" type="danger" icon="el-icon-delete" size="small"
              v-hasPermi="{v:['samples:retention:delete'],isF:activeIndex === '1'?true:false}"
              :disabled="multiple" @click="handlDes">批量销毁
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 表格 -->
        <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" border size="medium"
          :row-key="(row)=>{ return row.id}" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" :reserve-selection="true"
            v-if="activeIndex === '1'" />
          <el-table-column prop="sample_info.name" label="样品名称" align="center" />
          <el-table-column prop="sample_info.sample_type_name" label="样品类别" align="center" />
          <el-table-column prop="sample_info.batch_number" label="批号" align="center" />
          <el-table-column prop="sample_info.attr" label="规格" align="center" />
          <el-table-column label="生产日期" align="center">
            <template #default="{row}">
              <span v-if="row.sample_info !== null && row.sample_info.production_date">
                {{dateFormat1('yyyy-mm-dd HH:MM:SS',row.sample_info.production_date)}}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="num" label="留样数量" align="center" />
          <el-table-column prop="project_name" label="所属项目" align="center" />
          <el-table-column label="留样有效期至" align="center">
            <template #default="{row}">
              {{dateFormat1('yyyy-mm-dd HH:MM:SS',row.expiry_date)}}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="留样时间" align="center">
            <template #default="{row}">
              {{dateFormat1('yyyy-mm-dd HH:MM:SS',row.created_at)}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{row}">
              <el-button type="text" icon="el-icon-coordinate"
                v-hasPermi="{v:['samples:retention:add'],isF:(row.status === 1 && activeIndex === '1')?true:false}" 
                size="medium" 
                @click="handlAnd(row)">
                审批
              </el-button>
              <el-button type="text" icon="el-icon-view"  size="medium"
                v-hasPermi="{v:['samples:retention:report'],isF:activeIndex === '1'?true:false}" @click="hanldReport(row.inspection_id)">
                查看报告
              </el-button>
              <el-button type="text" icon="el-icon-delete" style="color:red"
                v-hasPermi="{v:['samples:retention:delete'],isF:(row.status === 0 && activeIndex === '1')?true:false}" size="medium" @click="handlDes(row)">
                销毁
              </el-button>
              <el-button type="text" icon="el-icon-view" v-hasPermi="{v:['samples:retention:details']}"
                size="medium" @click="hanldDetai(row.id)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--页码-->
        <pagination style="display:flex;justify-content:flex-end;" :total="total"
          :page.sync="queryParams.pager.skip" :limit.sync="queryParams.pager.limit"
          @pagination="pagination" />

        <!--弹框-->
        <el-dialog :title="title" :visible.sync="open" :width="widthOpen" append-to-body
          :before-close="cancel" :close-on-click-modal="false" v-if="open">
          <el-form :model="formOpen" ref="formOpen" label-width="120" :rules="rules">
            <!--审批-->
            <div v-if="openBoole === 1" class="box">
              <el-form-item label="审批意见" prop="check_advice">
                <el-input v-model="formOpen.check_advice" placeholder="请输入审批意见"
                  style="width:440px" />
              </el-form-item>
              <el-form-item label="审批结果" prop="check_status">
                <el-radio-group v-model="formOpen.check_status">
                  <el-radio :label="1">通过</el-radio>
                  <el-radio :label="2">不通过</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <!--销毁-->
            <div v-else-if="openBoole === 2">
              <el-table :data="formOpen.tableData" style="width: 100%" size="medium" border
                id="table">
                <el-table-column prop="sample_info.name" label="样品名称" align="center" />
                <el-table-column prop="sample_info.batch_number" label="批号" align="center" />
                <el-table-column prop="num" label="数量" align="center" />
                <el-table-column prop="name"  align="center" width="350">
                  <template #header>
                    <span style="color:red;line-height:16px ;">*</span>销毁原因
                  </template>
                  <template slot-scope="scope">
                    <el-form-item :prop="'tableData.'+scope.$index+'.destruction_reason'"
                      :rules="rules.destruction_reason">
                      <el-input v-model="scope.row.destruction_reason"
                        :disabled="scope.row.status !== 0"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </div>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button plain size="small" @click="cancel">取 消</el-button>
            <el-button size="small" type="primary" @click="submitForm">
              确定
            </el-button>
          </div>
        </el-dialog>

        <!--查看报告 -->
        <el-dialog title="查看报告" :visible.sync="openReport" width="600px" append-to-body
          :close-on-click-modal="false" v-if="openReport">
          <file-preview :file-list="fileList" :fileBtnOption="preview" />
          <div slot="footer" class="dialog-footer">
            <el-button plain size="small" @click="openReport = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {
  sampleList,
  destruction,
  destructionList,
  destructionApply
} from "@/api/samples";
import { viewReport } from "@/api/sampleInspection";
export default {
  data() {
    return {
      preview: ["preview"],
      activeIndex: "1",
      queryParams: {
        search_type: -1,
        sample_name: "",
        pager: {
          limit: 10,
          skip: 1
        }
      },
      options: [
        { value: -1, label: "全部" },
        { value: 0, label: "已留样" },
        { value: 1, label: "已过期" },
        { value: 2, label: "已销毁" }
      ],
      tableData: [],
      formOpen: {
        tableData: [],
        id: "",
        check_status: undefined,
        check_advice: ""
      },
      rules: {
        check_advice: [
          { required: true, message: "请输入审批意见", trigger: "blur" }
        ],
        check_status: [
          { required: true, message: "请选择审批结果", trigger: "change" }
        ],
        destruction_reason: [
          { required: true, message: "请输入名称", trigger: "blur" }
        ]
      },
      multipleSelection: [],
      multiple: true,
      open: false,
      total: 0,
      openBoole: 1,
      widthOpen: "",
      title: "",
      openReport: false,
      fileList: []
    };
  },
  //是计算属性，也可以理解为一个方法。
  computed: {},
  //属性是手动定义的所需监听的值
  watch: {},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.tabClick();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
  methods: {
    //切换tab
    tabClick() {
      if (this.activeIndex === "1") {
        this.hanldsampleList();
      } else {
        this.destructionList();
      }
    },

    //获取留样列表数据
    hanldsampleList() {
      sampleList(this.queryParams).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.data || [];
          this.total = res.data.total;
        }
      });
    },

    //获取销毁列表数据
    destructionList() {
      let data = {
        sample_name: this.queryParams.sample_name,
        pager: this.queryParams.pager
      };
      destructionList(data).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.data || [];
          this.total = res.data.total;
        }
      });
    },

    //页码
    pagination(val) {
      this.queryParams.pager.skip = val.page;
      this.queryParams.pager.limit = val.limit;
      this.hanldsampleList();
    },

    //查询
    handleQuery() {
      this.queryParams.pager.skip = 1;
      this.tabClick();
    },

    //重置
    resetQuery() {
      this.queryParams = {
        search_type: -1,
        sample_name: "",
        pager: {
          limit: 10,
          skip: 1
        }
      };
      this.tabClick();
    },

    //多选事件
    handleSelectionChange(selection) {
      this.multiple = !selection.length;
      this.multipleSelection = [...new Set(selection)];
    },

    //审批
    handlAnd(row) {
      this.openBoole = 1;
      this.formOpen.id = row.id;
      this.title = "审批意见";
      this.widthOpen = "600px";
      this.open = true;
    },

    //销毁
    handlDes(row) {
      this.openBoole = 2;
      this.formOpen.id = row.id;
      this.title = "销毁申请";
      this.widthOpen = "1000px";
      this.open = true;
      if (row.id) {
        this.formOpen.tableData = [row];
      } else {
        this.formOpen.tableData = this.multipleSelection;
      }
    },

    //查看报告
    hanldReport(id) {
      this.openReport = true;
      viewReport(id).then(res => {
        if (res.code === 200) {
          this.fileList = res.data || [];
        }
      });
    },

    //查看详情
    hanldDetai(id) {
      this.$router.push({
        path: "/samples/details",
        query: { id: id }
      });
    },

    //取消
    cancel() {
      this.open = false;
      this.formOpen = {
        tableData: [],
        id: "",
        check_status: undefined,
        check_advice: ""
      };
      this.$refs.multipleTable.clearSelection();
    },

    //提交
    submitForm() {
      this.$refs.formOpen.validate(valid => {
        if (valid) {
          let commit = undefined,
            data = {},
            msg = "";
          if (this.openBoole === 1) {
            commit = destruction;
            data = {
              id: this.formOpen.id,
              check_status: this.formOpen.check_status,
              check_advice: this.formOpen.check_advice
            };
            msg = "操作成功";
          } else {
            let arr = [];
            commit = destructionApply;
            this.formOpen.tableData.forEach(item => {
              if (item.status === 0) {
                arr.push({
                  id: item.id,
                  reason: item.destruction_reason
                });
              }
            });
            data = {
              apply_info: [...new Set(arr)]
            };
            msg = "操作成功";
            if (data.apply_info.length === 0) {
              this.$refs.multipleTable.clearSelection();
              this.open = false;
              this.cancel();
              this.hanldsampleList();
              return;
            }
          }
          commit(data).then(res => {
            if (res.code === 200) {
              this.$message.success(msg);
              this.open = false;
              this.cancel();
              this.hanldsampleList();
              this.$refs.multipleTable.clearSelection();
            }
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped  lang="scss">
::v-deep .el-tabs--border-card {
  box-shadow: 0 0 0 0;
}
::v-deep .el-button--text {
  padding: 0;
  margin: 0 !important;
  margin-right: 10px !important ;
}
.box ::v-deep .el-form-item__error {
  left: 76px;
}
#table {
  &.el-table--enable-row-hover {
    ::v-deep .el-table__body tr:hover > td {
      background-color: transparent;
      
    }
  }
  ::v-deep .el-table__body {
    .el-table__row {
      td {
        padding: 5px !important;
        .cell {
          padding: 0px;
        }
        .el-form-item {
          margin-bottom: 0px;
          .el-input__inner {
            border-width: 0px;
            border-radius: 0px;
          }
          &.is-error {
            .el-input__inner {
              border-width: 1px;
            }
          }
        }
      }
    }
  }
}
</style>

